package com.andy.web.file.service;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.andy.domain.result.BaseResult;
import com.andy.util.CharactorUtil;
import com.andy.web.util.SessionUtil;

@Service
public class FileService implements InitializingBean{

	private Logger LOGGER = LoggerFactory.getLogger(FileService.class);

	//开发环境文件上传路径
	public static final String UPLOAD_PATH_DEV = "E:/fileuploaded/";
	
	//生产环境文件上传路径
	public static final String UPLOAD_PATH_PROD = "/home/ubuntu/fileuploaded/";
	
	public static String PATH_2_UPLOAD = UPLOAD_PATH_DEV;
	
	public BaseResult upload2PythonServer(CommonsMultipartFile file, HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException {
		BaseResult res = new BaseResult();
		
		String fileNameContainingPath = "";
		String fileFullname = "";// 无盘符
		try {
			LocalDate now = LocalDate.now();
			DateTimeFormatter df = DateTimeFormatter.ofPattern( "yyyyMMdd" );
			fileFullname = now.format(df) + SessionUtil.getSession().getId()
					+ file.getOriginalFilename();
			fileNameContainingPath = PATH_2_UPLOAD + fileFullname;
			file.transferTo(new File(fileNameContainingPath));
		} catch (Exception e) {
			LOGGER.error(String.format("生成文件url出错, error stack:[%s]", e.getMessage()));
			res.setCode(5000);
			res.setMessage(e.getMessage());
			res.setValue("");
			return res;
		}
		
		res.setCode(200);
		res.setMessage("生成成功");
		res.setValue("http://andywei.club:9999/"
				+ (CharactorUtil.containsChineseStr(fileFullname)
						? URLEncoder.encode(fileFullname, "GBK")
						: fileFullname));
		return res;
	}
	
	public static void main(String[] args) throws UnknownHostException {
		InetAddress addr = InetAddress.getLocalHost();
		System.out.println(".."+addr.getHostAddress());
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		PATH_2_UPLOAD = UPLOAD_PATH_PROD;
	}
}
